package tech.moya.flexbase.components
{
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.data.SQLResult;
	import flash.events.Event;
	
	import mx.containers.Panel;
	import mx.controls.Button;
	import mx.controls.TextArea;
	import mx.events.FlexEvent;
	
	import mx.controls.Alert;
	
	import tech.moya.flexbase.core.BaseContext;
	import tech.moya.flexbase.core.ui.ApplicationContext;
	
	public class QueryPanel extends Panel
	{
		private var queryArea:TextArea;
		private var executeButton:Button;
		
		
		public function QueryPanel(panelTitle:String=""){
			super();
			
			
			label = panelTitle;
			title = panelTitle;	
			
			initComponents();
			
		}
		
		public function onExecuteClikecd(event:Event){
			var me:Button = Button(event.currentTarget);
			var bContext:BaseContext = BaseContext.getQueryPanelContext(QueryPanel(me.parent));
			var conn:SQLConnection = null;
			var stmt:SQLStatement = new SQLStatement();
			var result:SQLResult = null;
			var rows:Number = 0;
			var out:String = "";
			var colStr:String = "";

			try{
				conn = bContext.openConnection();
				stmt.sqlConnection = conn;
				stmt.text = this.queryArea.text;
				stmt.execute();
	
				result = stmt.getResult();
				rows = result.rowsAffected;
				trace("results returned from execution: "+rows);
				if(result.data != null){
					
					trace("getting data");
					for(var x:int =0;x<result.data.length;x++){
						for(var y:* in result.data[x]){
							if(x == 0){
								colStr+=y+"\t";
							}
							out+=result.data[x][y]+"\t";
						}
						out += "\n";
					}
					out = colStr+"\n"+out;			
				}else {
					out = rows +"rows were affacted.";
				}
				
				ApplicationContext.getCurrentApplicationContext().setOutputText(out);
			}catch(e:Error){
				Alert.show(e.getStackTrace(),e.name)
			}finally{	
				bContext.closeConnection(conn);
			}
		} 	
		
		private function initComponents():void{
			queryArea = new TextArea();
			
			this.layout = "absolute";
			queryArea = TextArea(super.addChild(queryArea));
			queryArea.setConstraintValue("top",25);
			queryArea.setConstraintValue("left",0);
			queryArea.setConstraintValue("right",0);
			queryArea.setConstraintValue("bottom",0);
			
			/***********Button*******************/
			
			executeButton = new Button();
			executeButton.label = "Execute";
			this.addChild(executeButton);
			executeButton.setConstraintValue("top",0);
			executeButton.setConstraintValue("left",0);
			executeButton.height = 20;
			executeButton.addEventListener(FlexEvent.BUTTON_DOWN,onExecuteClikecd);
			
			
			
			this.validateSize(true);
			this.validateNow();
			this.invalidateSize();
			
		}
		
		
		
		

	}
}
